<template>
  <view class="message-list-container">
    <view class="message-list">
      <view 
        class="message-item" 
        v-for="(message, index) in messageList" 
        :key="message.id || index" 
        @click="goToChat(message)"
      >
        <u-avatar :src="message.avatar" size="50"></u-avatar>
        <view class="message-content">
          <view class="message-header">
            <text class="sender-name">{{ message.senderName }}</text>
            <text class="message-time">{{ message.time }}</text>
          </view>
          <text class="message-preview">{{ message.lastMessage }}</text>
        </view>
        <u-badge :count="message.unreadCount" v-if="message.unreadCount > 0"></u-badge>
      </view>
      
      <!-- 空状态 -->
      <view v-if="messageList.length === 0" class="empty-state">
        <text class="empty-text">暂无消息</text>
      </view>
    </view>
  </view>
</template>

<script>
import { getConversationList } from '@/api/message'
import { formatTime } from '@/utils/date'

export default {
  data() {
    return {
      messageList: [],
      loading: false,
      currentUserId: null
    }
  },
  
  onLoad() {
    // 获取当前用户ID
    const userInfoStr = uni.getStorageSync('edu_user_info')
    const userInfo = userInfoStr ? JSON.parse(userInfoStr) : null
    this.currentUserId = userInfo ? userInfo.userId : null  // 修改：使用userId字段
    
    console.log('消息列表页面，当前用户ID:', this.currentUserId)
    
    this.loadConversations()
  },
  
  onShow() {
    // 每次显示页面时刷新会话列表
    this.loadConversations()
  },
  
  onPullDownRefresh() {
    this.loadConversations()
    setTimeout(() => {
      uni.stopPullDownRefresh()
    }, 1000)
  },
  
  methods: {
    async loadConversations() {
      if (this.loading) return
      
      this.loading = true
      
      try {
        const res = await getConversationList()
        
        console.log('API返回数据:', res)
        console.log('res.code:', res.code)
        console.log('res.data:', res.data)
        
        if (res.code === 200 && res.data && Array.isArray(res.data)) {
          console.log('===== 会话列表数据 =====')
          console.log('数据数量:', res.data.length)
          
          // 清空现有列表
          this.messageList = []
          
          // 处理每个会话
          res.data.forEach((conv, index) => {
            console.log(`\n会话${index + 1}:`, conv)
            
            // 提取数据
            const senderName = conv.otherUserName || conv.name || '未知用户'
            const avatar = conv.otherUserAvatar || conv.avatar || '/static/icons/default-avatar.png'
            
            console.log('姓名:', senderName)
            console.log('头像:', avatar)
            
            this.messageList.push({
              id: conv.id,
              conversationId: conv.id,
              senderName: senderName,
              avatar: avatar,
              lastMessage: conv.lastMessageContent || '暂无消息',
              time: this.formatTimeString(conv.updatedAt || conv.createdAt),
              unreadCount: conv.unreadCount || 0,
              otherUserId: conv.otherUserId
            })
          })
          
          console.log('\n最终messageList:', JSON.parse(JSON.stringify(this.messageList)))
        } else {
          console.warn('API返回数据格式不正确:', res)
          this.messageList = []
        }
      } catch (error) {
        console.error('===== 加载会话列表失败 =====')
        console.error('错误信息:', error)
        console.error('错误堆栈:', error.stack)
        
        // 显示空列表
        this.messageList = []
        
        uni.showToast({
          title: '加载失败',
          icon: 'none',
          duration: 2000
        })
      } finally {
        this.loading = false
      }
    },
    
    
    // 格式化时间字符串（避免formatTime抛异常）
    formatTimeString(timeStr) {
      try {
        return formatTime(timeStr)
      } catch (error) {
        console.error('formatTime错误:', error)
        return '刚刚'
      }
    },
    
    goToChat(message) {
      console.log('点击会话:', message)
      // 跳转时传递对方用户ID
      const url = `/pages/message/chat?conversationId=${message.conversationId}&name=${encodeURIComponent(message.senderName)}&otherUserId=${message.otherUserId}`
      console.log('跳转URL:', url)
      uni.navigateTo({
        url: url
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.message-list-container {
  background: #f5f5f5;
  min-height: 100vh;
}

.message-list {
  background: white;
  min-height: 100vh;
  
  .message-item {
    display: flex;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #f0f0f0;
    position: relative;
    transition: background-color 0.3s;
    
    &:active {
      background-color: #f8f8f8;
    }

    &:last-child {
      border-bottom: none;
    }
    
    .message-content {
      flex: 1;
      margin-left: 20rpx;
      
      .message-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 12rpx;
        
        .sender-name {
          font-size: 30rpx;
          font-weight: 600;
          color: #333;
        }
        
        .message-time {
          font-size: 24rpx;
          color: #999;
        }
      }
      
      .message-preview {
        font-size: 28rpx;
        color: #666;
        line-height: 1.4;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
      }
    }

    /deep/ .u-avatar {
      box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
    }

    /deep/ .u-badge {
      transform: scale(0.9);
    }
  }
}

.empty-state {
  padding: 100rpx;
  text-align: center;
  
  .empty-text {
    font-size: 28rpx;
    color: #999;
  }
}
</style> 